package com.hoolai.qps.codes.netty.client;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.google.protobuf.Message;
import com.hoolai.qps.netty.proto.Client.Cmd;

public class ClientEncoder extends OneToOneEncoder {

    @Override
    protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
        if(!(msg instanceof Cmd)){
            return msg;
        }
        Cmd cmd = (Cmd) msg;
        ChannelBuffer buf = null;
        Message proto = cmd.getMessage();
        byte[] bytes = proto.toByteArray();
        buf = ChannelBuffers.buffer(4 + 4 + 4 + bytes.length);//一个报文长度   一个命令id 一个channelid
        buf.writeInt(bytes.length + 4 + 4);//报文 length
        buf.writeInt(cmd.getCmdId());//命令id
        buf.writeInt(0);//channel id
        buf.writeBytes(bytes);
        return buf;
    }

}
